﻿#include <QGraphicsScene>
#include <QWheelEvent>
#include <QDebug>
#include "JZImageView.h"

JZGraphicItem::JZGraphicItem(JZGraphic g)
{
    m_graphic = g;
    updateBoundingRect();
}

void JZGraphicItem::updateBoundingRect()
{
    auto &points = m_graphic.points;
    if (points.isEmpty())
    {
        m_rect  = QRectF(); // 返回空矩形
        return;
    }

    // 初始化最小和最大值为第一个点的坐标
    qreal minX = points[0].x();
    qreal minY = points[0].y();
    qreal maxX = points[0].x();
    qreal maxY = points[0].y();

    // 遍历所有点，更新最小和最大值
    for (const QPointF& point : points) {
        minX = qMin(minX, point.x());
        minY = qMin(minY, point.y());
        maxX = qMax(maxX, point.x());
        maxY = qMax(maxY, point.y());
    }

    // 使用最小点和尺寸构建矩形
    m_rect = QRectF(minX, minY, maxX - minX, maxY - minY);
}

QRectF JZGraphicItem::boundingRect() const
{
    return m_rect;
}

void JZGraphicItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    m_graphic.draw(painter);
}

//JZImageView
JZImageView::JZImageView()
{
    m_scene = new QGraphicsScene();
    setScene(m_scene);

    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    setDragMode(QGraphicsView::ScrollHandDrag);
    setViewportUpdateMode(QGraphicsView::FullViewportUpdate);
    setCacheMode(QGraphicsView::CacheBackground);
    setMouseTracking(true);
}

JZImageView::~JZImageView()
{
}

QImage JZImageView::image()
{
    return m_image;
}

void JZImageView::setImage(const QImage &image)
{
    m_image = image;
    setSceneRect(image.rect());
    clearGraphics();    
    scene()->invalidate(scene()->sceneRect());
}

void JZImageView::clear()
{
    m_image = QImage();
    clearGraphics();
    scene()->invalidate(scene()->sceneRect());
}

void JZImageView::wheelEvent(QWheelEvent *event)
{
    if (event->angleDelta().y() > 0)
        scale(1.05, 1.05);
    else
        scale(0.95, 0.95);        
}

 void JZImageView::mouseMoveEvent(QMouseEvent *event)
 {
    QGraphicsView::mouseMoveEvent(event);

    QPoint scenePos = mapToScene(event->pos()).toPoint();
    if(m_image.rect().contains(scenePos))
    {
        QColor color = m_image.pixelColor(scenePos);
        emit sigCoorColor(scenePos, color);
    }
}

void JZImageView::initGraphics(const QList<JZGraphic> &graphic)
{
    m_scene->clear();
    for (int i = 0; i < graphic.size(); i++)
    {
        auto* g = new JZGraphicItem(graphic[i]);
        m_scene->addItem(g);
    }
}

void JZImageView::clearGraphics()
{
    m_scene->clear();
}

void JZImageView::drawBackground(QPainter* painter, const QRectF& r)
{    
    painter->fillRect(r,Qt::white);
    painter->drawImage(0, 0, m_image);    
}